package api

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"chaincode/model"
	"chaincode/pkg/utils"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

func CheckCredit(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	// 公安局认证
	// 接收:姓名 身份证号

	data, err := utils.GetStateByPartialCompositeKeys2(stub, model.CreditKey, args)

	if err != nil {
		return shim.Error(fmt.Sprintf("%s", err))
	}
	var CreditList []model.Credit
	for _, v := range data {
		if v != nil {
			var creditInfo model.Credit
			err = json.Unmarshal(v, &creditInfo)
			if err != nil {
				return shim.Error(fmt.Sprintf("QueryRealEstateList-反序列化出错: %s", err))
			}
			CreditList = append(CreditList, creditInfo)
		}
	}
	if len(CreditList) == 0 {
		return shim.Error("false")
	}

	marshal, err := json.Marshal(CreditList)
	if err != nil {
		return shim.Error("false")
	}
	return shim.Success(marshal)

}

// 公安局上链智能合约
func AddCredit(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	// 接收数据: 姓名 身份证号

	if len(args) != 3 {
		return shim.Error("Incorrect number of arguments. Expecting 3")
	}

	creditinfo := &model.Credit{
		Name:   args[0],
		Code:   args[1],
		IsLock: args[2],
	}

	// 获取当前时间
	t := time.Now()

	// 加载上海时区
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println("时区加载错误:", err)
		return shim.Error(err.Error())
	}

	// 将当前时间转换为上海时区的时间
	shanghaiTime := t.In(loc)

	// 格式化时间为字符串，例如："2006-01-02 15:04:05"
	formattedTime := shanghaiTime.Format("2006-01-02 15:04:05")
	un := strconv.Itoa(int(time.Now().Unix()))

	err = utils.WriteLedger(creditinfo, stub, model.CreditKey, []string{creditinfo.Name, creditinfo.Code, formattedTime, un})
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(nil)
}
